package com.xingshentech.ugv.operate.module.httpdata

import com.xingshentech.utils.SecurityUtil
import okhttp3.*
import okio.Buffer

class DataEncryptInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        if (request.method().equals("POST")) {
//                在 Kotlin 中，val 是一个 不可变变量（只读变量），类似于 Java 中的 final 变量。
            val isMultipart = isMultipartFormData(request)
            //如果是post 传文件 不加密
            if (isMultipart) {
                return chain.proceed(request)
            }
            // 获取原始的请求体
            val requestBody = request.body()
            if (requestBody != null) {
                var content: String? = null
                val buffer = Buffer()
                requestBody.writeTo(buffer)
                content = buffer.readUtf8()
//                XsLog.e("requestUrl=${request.url().url()}}", content)
                val encryptedData: String =
                    String(SecurityUtil.gmSm4CbcEncryptData(content.toByteArray(), true))
                // 使用加密后的数据创建新的请求体
                val newRequestBody = RequestBody.create(requestBody.contentType(), encryptedData)
                // 使用新的请求体创建新的请求
                val newRequest = request.newBuilder().post(newRequestBody).build()
                return chain.proceed(newRequest)
            }
        }
        if (request.method() == "GET") {
            val originalHttpUrl: HttpUrl = request.url()
            val newHttpUrlBuilder = originalHttpUrl.newBuilder()
            //get请求 key=value 对每一个value进行加密操作
            for (paramName in originalHttpUrl.queryParameterNames()) {
                val paramValue = originalHttpUrl.queryParameter(paramName)
                val encryptedValue: String = String(
                    SecurityUtil.gmSm4CbcEncryptData(
                        paramValue?.toByteArray(),
                        true
                    )
                )
                newHttpUrlBuilder.setQueryParameter(paramName, encryptedValue)
            }
            val newHttpUrl = newHttpUrlBuilder.build()
            val newRequest: Request = request.newBuilder()
                .url(newHttpUrl)
                .build()
            return chain.proceed(newRequest)
        }
        return chain.proceed(request)
    }


    private fun isMultipartFormData(request: Request): Boolean {
        val contentType = request.header("Content-Type")
        return contentType != null && contentType.startsWith("multipart/form-data")
    }
}
